package com.cloudpan.controller;

/**
 * @Author sc
 * @DATE 2024/1/29 17:05
 * @Description:
 * @Version 1.0
 */

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudpan.common.R;
import com.cloudpan.common.exception.GlobalExceptionHandler;
import com.cloudpan.entity.pojo.SysFileInfo;
import com.cloudpan.service.SysFileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author sc
 * @DATE 2024/1/29 13:52
 * @Description:
 * @Version 1.0
 */
@RestController
@RequestMapping("/sys/view")
@RequiredArgsConstructor
@Api(value = "文件预览控制层", tags = "文件预览控制层")
public class SysFileViewController {

    private final SysFileInfoService fileInfoService;

    @Value("${kkview.viewUrl}")
    private String viewUrl;

    /**
     *  根据文件id和用户id查询到用户的文件信息 从而查询到文件的url信息
     * @param fid 文件id
     * @param uid 用户id
     * @return 为了方便 直接全部写在控制层
     *
     */
    @GetMapping("/fileview/{uid}/{fid}")
    @ApiOperation(value = "文件预览功能,采用开源项目kkview")
    public R fileView(@PathVariable("fid") String fid, @PathVariable("uid") String uid){
        LambdaQueryWrapper<SysFileInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysFileInfo::getFileId,fid)
                .eq(SysFileInfo::getUserId,uid);

        SysFileInfo fileInfo = fileInfoService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(fileInfo)){
            throw new GlobalExceptionHandler("文件Url不存在");
        }
        String fileUrl = fileInfo.getFileUrl();
        String encode = Base64.encode(fileUrl.getBytes());
        String url = viewUrl + encode;
        return R.ok(url);
    }

}
